import { data } from './data.js'
class store {
  constructor() {
    this.globalData = data
    this.setList = []
  }
  //去除已删除页面栈方法（不能直接调用）
  shiftPage(page) {
    if (page.route.indexOf('tab_') !== -1) {
      return true
    } else {
      return page.isOver != false
    }
  }
  //更新方法（不能直接调用）
  upData() {
    //获取页面栈
    var pages = getCurrentPages();
    let list = this.setList
    list.forEach((value, index, _this) => {
      _this[index].isOver = false
      for (let i of pages) {
        if (i.__wxExparserNodeId__ === value.id) {
          _this[index].isOver = true
          let dataList = {};
          for (let item of value.dataList.keys()) {
            dataList[item] = this.globalData[item]
          }
          i.setData({
            ...dataList
          })
          break
        }
      }
    })
    this.setList = list.filter(this.shiftPage);
  }
  //赋值方法
  setProps(data,callback) {
    if(!data){
      return
    }
    //给globalData赋值
    for (let i in data) {
      this.globalData[i] = data[i]
    }
    if(callback){
      callback(data)
    }
    //开始更新
    this.upData()
  }
  //取值方法(会双向绑定)
  getProps(key, _this) {
    const pageId = _this.__wxExparserNodeId__;
    const pageRoute = _this.__route__;
    const list = this.setList;
    let isHas = false;
    if (list.length != 0) {
      for (let i = 0; i < list.length; i++) {
        if (list[i].id === pageId) {
          isHas = i
          break
        }
      }
    }
    //判断有没有这个页面队列
    if (isHas === false) {
      let dataList = new Set();
      dataList.add(key);
      // for (let i in key) {
      //   dataList.add(i);
      // }
      list.unshift({
        id: pageId,
        route: pageRoute,
        dataList
      })
    } else {
      let dataList = list[isHas].dataList;
      dataList.add(key);
    }
    return this.globalData[key]
  }
  //只取值不绑定
  getData(key){
    let newData = this.globalData[key];
    if(newData || newData === 0){
      return newData
    }else{
      return null
    }
  }
  //清除数据
  removeProps(data){
    if(!data){
      return
    }
    this.globalData[data] = null
    this.upData()
    return this
  }
}
let $store = new store()
module.exports = {
  $store
}